using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Newtonsoft.Json.Linq;

namespace JsonRpcGen.TypeHandler
{
    internal class MultiBaseType : TypeHandler
    {
        private readonly JToken _properties;
        private readonly JToken _baseNames;
        private List<string> classes;
        private string _className;
        private string _baseInterface;

        public MultiBaseType(JToken properties, JToken baseNames)
        {
            _properties = properties;
            _baseNames = baseNames;
        }

        public MultiBaseType(JToken properties, MultiBaseType multiBaseType)
        {
            _properties = properties;
            _baseNames = JToken.FromObject(multiBaseType.classes);
            _baseInterface = multiBaseType._className;

        }

        public override void Write(StreamWriter writer, string namesp, string className, Dictionary<string, string> replacements)
        {
            writer.WriteLine("namespace " + namesp);
            writer.WriteLine("{");

            classes = new List<string>();
            _className = namesp + "." + className;
            foreach (var baseName in _baseNames)
            {
                var typeHandler = new ObjectTypeHandler(_properties, baseName.ToString()+ ","+className);
                var parts = baseName.ToString().Split('.');
                typeHandler.WriteClass(writer, className + parts.Last(), replacements,false);
                classes.Add(namesp + "." + className + parts.Last());
            }

            var interfaceHandler = new ObjectTypeHandler(_properties, _baseInterface);
            interfaceHandler.WriteInterface(writer, className, replacements);
            interfaceHandler.WriteNestedClasses(writer,replacements);
            writer.WriteLine("}");

            CreateConverter(className, classes, namesp);
        }

        private void CreateConverter(string interfaceName, List<string> classes, string namesp)
        {
            if(classes.Count!=2)
            {
                throw new NotImplementedException();
            }
            var converter = File.ReadAllText("Templates\\Converter.templ");
            converter=converter.Replace("%interface_name%", interfaceName);
            converter = converter.Replace("%interface_fullname%", namesp + "." + interfaceName);
            converter = converter.Replace("%class1_fullname%", classes[0]);
            converter = converter.Replace("%class2_fullname%", classes[1]);
            File.WriteAllText(Path.Combine(Global.TargetDir.FullName, interfaceName+"Converter.cs"), converter);
        }
    }
}